package com.lhd_gm.scheduledtasksystem.listener;

import com.lhd_gm.scheduledtasksystem.pojo.JobLog;
import com.lhd_gm.scheduledtasksystem.service.JobLogService;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class JobLogListener implements JobListener {
    private static final Logger logger = LoggerFactory.getLogger(JobLogListener.class);
    @Autowired
    @Lazy
    private JobLogService jobLogService;

    @Override
    public String getName() {
        return "JobLogListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext jobExecutionContext) {
        JobLog jobLog = new JobLog();
        JobDetail jobDetail = jobExecutionContext.getJobDetail();
        jobLog.setJobName(jobDetail.getKey().getName());
        jobLog.setGroupName(jobDetail.getKey().getGroup());
        jobLog.setStartTime(LocalDateTime.now());
        jobLogService.jobLogSave(jobLog);
        jobExecutionContext.put("logId", jobLog.getId()); // 存储日志ID用于后续更新
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) {
        logger.info("Job {} execution vetoed", jobExecutionContext.getJobDetail().getKey());
    }

    @Override
    public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException jobException) {
        Long logId = (Long) jobExecutionContext.get("logId");
        JobLog jobLog = jobLogService.findJobLogById(logId).orElse(null);
        if (jobLog != null) {
            jobLog.setEndTime(LocalDateTime.now());
            if (jobException != null) {
                jobLog.setResult("FAILURE");
                jobLog.setException(jobException.getMessage());
            } else {
                jobLog.setResult("SUCCESS");
            }
            jobLogService.jobLogSave(jobLog);
        }
    }
}
